import {
  Controller,
  Post,
  UseInterceptors,
  UploadedFile,
  BadRequestException
} from '@nestjs/common';

import { FileInterceptor } from '@nestjs/platform-express';
import { Express } from 'express';
import * as path from 'path';

import { fileStorage } from './utils/file-storage';

@Controller('upload')
export class UploadController {

  @Post('picture')
  @UseInterceptors(
    FileInterceptor('picture', {
      dest: 'uploads',
      storage: fileStorage,
      // 限制图片大小
      limits: {
        fileSize: 1024 * 1024 * 2 // 2M
      },
      // 限制图片格式
      fileFilter(req, file, callback) {
        const extname = path.extname(file.originalname);
        if (['.png', '.jpg', '.gif', '.jpeg'].includes(extname)) {
          callback(null, true);
        } else {
          callback(new BadRequestException('只能上传图片！'), false);
        }
      }
    })
  )
  uploadPicture(@UploadedFile() file: Express.Multer.File) {
    return file;
  }
}

